import React, { useEffect, useState } from "react";
import { InfiniteScroll, PullToRefresh, List, Avatar, Image, Toast, Radio, DotLoading } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import styles from './index.module.less'
import { EyeFill, DeleteOutline } from 'antd-mobile-icons'
const { getTemplateList, setDefalutTemplate } = $globalServicer('chat')

const TemplateList = (props) => {
  const { tabType } = props;
  const customNavigate = $globalNavigate()
  const [data, setData] = useState([]);
  const [templateList, setTemplateList] = useState([]);
  const [loading, setLoading] = useState(false);
  const fetchTemplateList = async () => {
    setLoading(true)
    const res = await getTemplateList();
    if (Array.isArray(res)) {
      setTemplateList(res)
    } else {
      setTemplateList([])
    }
    setLoading(false)
  }
  const InfiniteScrollContent = ({ loading }) => {
    return (
      <>
        {loading ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 已到达底部 ---</span>
        )}
      </>
    )
  }
  const handleSetDefaultTemplate = async (templateId) => {
    const res = await setDefalutTemplate({ id: templateId })
    if (res.length === 0) {
      Toast.show({
        icon: 'success',
        content: `设置成功`,
      })
      fetchTemplateList()
      handleSetSessionItem('childReloads', true);
    }
  }
  const handleSetSessionItem = (key, value) => {
    console.log(`--------window`, window);
    console.log(`--------window`, window.parent);
    sessionStorage.setItem(key, value);
    const parentWindow = window;
    parentWindow.sessionStorage.setItem(key, value);
    // parentWindow.reloadPage();
    // window.parent.jg_reload()
  }
  useEffect(() => {
    fetchTemplateList()
  }, [tabType]);

  return (
    <div className={styles.chatListItemWrapper}>
      <PullToRefresh
        key={tabType}
        onRefresh={async () => {
          await fetchTemplateList()
          Toast.show({
            icon: 'success',
            content: `刷新成功`,
          })
        }}
      >
        <div className={styles.item_list}>
          <div className={styles.item_list_header}>
            <p>对话预设为全局预设，在所有对话中均生效，请根据世界选择不同预设。</p>
          </div>
          <List>
            {templateList?.map((templateItem, index) => (
              <List.Item
                key={templateItem.id}
              >
                <div className={styles.headerSection}>{templateItem.name}</div>
                <div className={styles.contentSection}>
                  {templateItem.template.map(f => (
                    <div className={styles.contentItem} key={f.id}
                      style={{
                        backgroundImage: `url(${f.cover})`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center'
                      }}
                    >
                      <div className={styles.contentItemTitle}>
                        <p className={styles.contentItemTitleText}>{f.name}</p>
                      </div>
                      <div className={styles.radioWrapper}>
                        <Radio
                          value='small'
                          style={{
                            '--icon-size': '18px',
                            '--font-size': '14px',
                            '--gap': '6px',
                          }}
                          onChange={(value) => {
                            console.log(`------value`, value)
                            handleSetDefaultTemplate(f.id)
                          }}
                          checked={f.default === 1}
                        >
                        </Radio>
                      </div>

                      <div className={styles.contentItemDesc}>{f.summary}</div>
                    </div>
                  ))}
                </div>
              </List.Item>
            ))}
          </List>
        </div>
        <InfiniteScroll threshold={20} >
          <InfiniteScrollContent loading={loading} />
        </InfiniteScroll>
      </PullToRefresh>
    </div>
  );
};

export default TemplateList;
